﻿using System.ComponentModel;
using System.Linq;
using VNPT;
using System.IO;
using System.Windows.Forms;
using System;
using VNPT.Data;

namespace VNPT.DoiSoat
{
    public partial class uNoiFile : Core.uBase
    {
        public uNoiFile()
        {
            InitializeComponent();

            bgWork.RunWorkerCompleted += (a, e) =>
            {
                SauKhiChay();
                

                labelControl4.Text = "Đã hoàn thành...";
                progressBarControl1.EditValue = progressBarControl1.Properties.Maximum;
                if (e.Error==null)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("Đã xử lý xong, vui lòng kiểm tra lại!","Hoàn thành!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(e.Error.Message,"Hoàn thành!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
                }
            };
            bgWork.ProgressChanged += (a, e) =>
            {
                progressBarControl1.EditValue = e.ProgressPercentage;
                labelControl4.Text = string.Format("Đang nối file {0}...", te);
                AppendTextBox(DateTime.Now.ToString("HH:mm:ss")+" "+ labelControl4.Text + Environment.NewLine);
            };
            bgWork.DoWork += (a, e) =>
            {
                ThucHien_HostBMT();
                ThucHien_TanLoi();
            };
        }
        public void AppendTextBox(string value)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
                return;
            }
            memoEdit1.Text = value + memoEdit1.Text;
        }

        public override void LoadSetting()
        {
            Load();
            base.LoadSetting();
        }

        public override void SaveSetting()
        {
            Save();
            base.SaveSetting();
        }
        private void Load()
        {
            btnThuMucBMT.Text = DoiSoatSetting.Folder_BMT;
            btnThuMucTanLoi.Text = DoiSoatSetting.Folder_TANLOI;
            btnThuMucLuu.Text = DoiSoatSetting.Folder_LUU;
        }
        private void Save()
        {
           DoiSoatSetting.Folder_BMT= btnThuMucBMT.Path;
           DoiSoatSetting.Folder_TANLOI = btnThuMucTanLoi.Path;
           DoiSoatSetting.Folder_LUU = btnThuMucLuu.Path;
        }
        string te = "";

        private void ThucHien_HostBMT()
        {
            string SourceStr = string.Format(@"Provider=vfpoledb;Data Source={0};", DoiSoatSetting.Folder_LUU);
            DbNetData SourceConnection = new DbNetData(SourceStr, DataProvider.OleDb);

            DbNetData Db = new DbNetData(SourceStr, DataProvider.OleDb);
            Db.Open();

            var fileName = string.Format("CT_HOST_810_{0}_{1}_DLK", DoiSoatSetting.NAM, DoiSoatSetting.THANG.ToString("D2"));
            var strSQL = string.Format(@"create table {0}
                                        (CHUGOI    CHARACTER(22) Not NULL  ,
                                          BIGOI     CHARACTER(22) Not NULL ,
                                          NGAYBD    DATE Not NULL,
                                          GIOBD     CHARACTER(8) Not NULL,
                                          TGGOI     NUMERIC(6) Not NULL,
                                          PHUT      NUMERIC(10) Not NULL,
                                          INC_ROUTE CHARACTER(10) Not NULL,
                                          OUT_ROUTE CHARACTER(10) Not NULL)", fileName);

            QueryCommandConfig Query = new QueryCommandConfig(strSQL);
            Db.ExecuteNonQuery(Query);

            var files = Directory.GetFiles(DoiSoatSetting.Folder_BMT).Where(p => p.ToUpper().EndsWith(".DBF"));
            int i = 0;
            foreach (var item in files)
            {
                i++;
                if (bgWork.CancellationPending)
                {
                    continue;
                }
                te = item;
                var sql = string.Format(@"INSERT INTO {0} (CHUGOI, BIGOI, NGAYBD, GIOBD, TGGOI, INC_ROUTE, OUT_ROUTE, PHUT)
                                          SELECT CHUGOI, BIGOI, NGAYBD, GIOBD, TGGOI, ALLTRIM(INC_ROUTE), ALLTRIM(OUT_ROUTE), CEILING(TGGOI/60) AS PHUT
                                          FROM {1} Where Month(NGAYBD)={2} AND BIGOI IS NOT NULL AND INC_ROUTE IS NOT NULL", fileName, item, DoiSoatSetting.THANG);
                QueryCommandConfig Query2 = new QueryCommandConfig(sql);
                Db.ExecuteNonQuery(Query2);
                bgWork.ReportProgress(i * 100 / files.Count());
            }

            Db.Close();
        }
        private void ThucHien_TanLoi()
        {
            string SourceStr = string.Format(@"Provider=vfpoledb;Data Source={0};", DoiSoatSetting.Folder_LUU);
            DbNetData SourceConnection = new DbNetData(SourceStr, DataProvider.OleDb);

            DbNetData Db = new DbNetData(SourceStr, DataProvider.OleDb);
            Db.Open();
           var fileName = string.Format("CT_HOST_TanLoi_{0}_{1}_DLK", DoiSoatSetting.NAM, DoiSoatSetting.THANG.ToString("D2"));
            var strSQL = string.Format(@"create table {0}
                                        ( CHUGOI    CHARACTER(22)  Not NULL,
                                          BIGOI     CHARACTER(22) Not NULL,
                                          NGAYBD    DATE Not NULL,
                                          GIOBD     CHARACTER(8) Not NULL,
                                          TGGOI     NUMERIC(6) Not NULL,
                                          PHUT      NUMERIC(10) Not NULL,
                                          INC_ROUTE CHARACTER(10) Not NULL,
                                          OUT_ROUTE CHARACTER(10) Not NULL)", fileName);

            QueryCommandConfig Query = new QueryCommandConfig(strSQL);
            Db.ExecuteNonQuery(Query);



            var files = Directory.GetFiles(DoiSoatSetting.Folder_TANLOI).Where(p => p.ToUpper().EndsWith(".DBF"));

            int i = 0;
            foreach (var item in files)
            {
                i++;
                if (bgWork.CancellationPending)
                {
                    continue;
                }
                te = item;
                var sql = string.Format(@"INSERT INTO '{0}' (CHUGOI, BIGOI, NGAYBD, GIOBD, TGGOI, INC_ROUTE, OUT_ROUTE, PHUT)
                                          SELECT CHUGOI, BIGOI, NGAYBD, GIOBD, TGGOI, ALLTRIM(INC_ROUTE), ALLTRIM(OUT_ROUTE), CEILING(TGGOI/60) AS PHUT
                                          FROM '{1}' Where Month(NGAYBD)={2} AND BIGOI IS NOT NULL AND INC_ROUTE IS NOT NULL", fileName, item, DoiSoatSetting.THANG);
                QueryCommandConfig Query2 = new QueryCommandConfig(sql);
                Db.ExecuteNonQuery(Query2);
                bgWork.ReportProgress(i * 100 / files.Count());
            }

            Db.Close();
        }


        private void TruocKhiChay()
        {
            DevExpress.XtraEditors.XtraForm f;
            if (this.Parent == null) return;
            if (this.Parent.Parent == null) return;
            else
            {
                var t2 = this.Parent.Parent as DevExpress.XtraEditors.XtraForm;
                f = t2;
            }

            var t = this.Parent.Parent.Parent as DevExpress.XtraEditors.XtraForm;
            if (t != null)
            {
                f = t;
            }
            if (f != null)
            {
                f.FormClosing += (a1, e1) =>
                {
                    if (bgWork.IsBusy)
                    {
                        string text = "Chương trình đang chạy, không thể đóng form! Vui lòng hủy trước khi đóng chương trình?";
                        string caption = "Xác nhận?";
                        DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        e1.Cancel = true;
                    }
                };

            }

            var m = this.Parent as DevExpress.XtraWizard.WizardPage;
            if (m != null)
            {
                m.AllowNext = false;
                m.AllowBack = false;
            }
        }

        private void SauKhiChay()
        {
            var m = this.Parent as DevExpress.XtraWizard.WizardPage;
            if (m != null)
            {
                m.AllowNext = true;
                m.AllowBack = true;
            }
        }

        private void myButtonEdit1_Click(object sender, System.EventArgs e)
        {
            TruocKhiChay();
            bgWork.RunWorkerAsync();
        }

        private void btnDung_Click(object sender, System.EventArgs e)
        {
            string text = "Bạn chắc có muốn dừng thực hiện không?";
            string caption = "Hủy bỏ?";
            if (DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                this.bgWork.CancelAsync();
            }
        }

    }
}
